package com.tiandang.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

@Service
public class SendMessageService {
  // 调用短信通道发送短信
  public SendResult sendMessage(String phone, String text) {
    String params = "action=send&userid=1711&account=QBCYZM&password=a123456&mobile=" + phone + "&content=" + text
      + "&sendTime=&extno=";
    SendResult sendResult = getSendResult(sendPost("http://dx.10691.net:8888/sms.aspx", params));
    return sendResult;
  }

  /**
   * 向指定 URL 发送POST方法的请求
   *
   * @param url
   *            发送请求的 URL
   * @param param
   *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
   * @return 所代表远程资源的响应结果
   *         https://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html
   */
  public String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";

    try {
      URL realUrl = new URL(url);
      // 打开和URL之间的连接
      URLConnection conn = realUrl.openConnection();
      // 设置通用的请求属性
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 发送POST请求必须设置如下两行
      conn.setDoOutput(true);
      conn.setDoInput(true);
      // 获取URLConnection对象对应的输出流
      out = new PrintWriter(conn.getOutputStream());
      // 发送请求参数
      out.print(param);
      // flush输出流的缓冲
      out.flush();
      // 定义BufferedReader输入流来读取URL的响应

      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    // 使用finally块来关闭输出流、输入流
    finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return result;
  }

  public SendResult getSendResult(String xml) {

    SendResult sendResult = new SendResult();

    // 1.创建SAXReader的对象reader
    // SAXReader reader = new SAXReader();

    try {
      // 2.通过reader对象的read（）方法加载books.xml文件，获取document对象
      // Document document = reader.read(new File("src/returnsms.xml"));
      Document document = DocumentHelper.parseText(xml); // 将字符串转为XML

      // 3.通过document对象获取根节点returnsms
      Element returnsms = document.getRootElement();

      // 4.通过element对象的elementIterator获取迭代器
      Iterator it = returnsms.elementIterator();

      // 5.遍历迭代器，获取根节点中的信息
      while (it.hasNext()) {
        Element result = (Element) it.next();

        if (result.getName().equals("returnstatus")) {
          sendResult.setReturnstatus(result.getStringValue());
        } else if (result.getName().equals("message")) {
          sendResult.setMessage(result.getStringValue());
        } else if (result.getName().equals("remainpoint")) {
          sendResult.setRemainpoint(result.getStringValue());
        } else if (result.getName().equals("taskID")) {
          sendResult.setTaskID(result.getStringValue());
        } else if (result.getName().equals("successCounts")) {
          sendResult.setSuccessCounts(result.getStringValue());
        }

      }
    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // 输出保存在内存中XML信息
//		System.out.println("===输出开始====");
//		System.out.println(sendResult.getReturnstatus());
//		System.out.println(sendResult.getMessage());
//		System.out.println(sendResult.getRemainpoint());
//		System.out.println(sendResult.getTaskID());
//		System.out.println(sendResult.getSuccessCounts());
//		System.out.println("===输出结束===");

    return sendResult;
  }


}
